/**
 * Created by Freeman on 2016/6/27.
 */
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var compose = require('composable-middleware');
var settings = require('../../settings');
var User = require('../models/user.model');

/**
 * 验证token
 */
function authToken(credentialsRequired) {
    return compose()
        .use(function (req, res, next) {
            if (req.query && req.query.hasOwnProperty('access_token')) {
                req.headers.authorization = 'Bearer ' + req.query.access_token;
            }
            next();
        })
        .use(expressJwt({
            secret: settings.session.cookieSecret,
            credentialsRequired: credentialsRequired //是否抛出错误
        }))
}

/**
 * sns登录传递参数
 */
function snsPassport() {
    return compose()
        .use(authToken(false))
        .use(function (req, res, next) {
            req.session.passport = {
                redirectUrl: req.query.redirectUrl || '/'
            }
            if (req.user) {
                req.session.passport.userId = req.user._id;
            }
            next();
        });
}
/**
 * 生成token
 */
function signToken(id) {
    return jwt.sign({ _id: id }, settings.session.cookieSecret, { expiresIn: '1y' });
}

function isAuthenticated() {
    return compose()
        .use(authToken(true))
        .use(function(err,req,res,next){
            //expressJwt 错误处理中间件
            if (err.name === 'UnauthorizedError') {
                return res.status(401).send();
            }
            next();
        })
        .use(function (req,res,next) {
            User.findById(req.user._id,function (err,user) {
                if (err) return res.status(500).send();
                if (!user) return res.status(401).send();
                req.user = user;
                next();
            })
        })
}

exports.isAuthenticated = isAuthenticated;
exports.snsPassport = snsPassport;

exports.signToken = signToken;